<template>
  <div v-loading="loading" class="rc-cont">
    <div v-if="!isSeas" class="rc-head">
      <template v-if="teamEditAuth">
        <el-button icon="el-icon-plus" @click="handleClick('add')">
          {{ $t('crm.components.90056cd9deb9339352626b57cc16d19d') }}
        </el-button>
        <el-button @click="handleClick('edit')">
          {{ $t('crm.components.6934ef02bb0f5628ea7c6df7e8be7c1b') }}
        </el-button>
        <el-button @click="handleClick('delete')">
          {{ $t('crm.components.acc197c71d299c134ea5c8fb3816e8b1') }}
        </el-button>
        <el-button type="danger" @click="handleClick('exit')">
          {{ $t('crm.components.a251fc41293eb52da37164513d0d219e') }}
        </el-button>
      </template>
    </div>
    <el-table
      :data="list"
      :height="tableHeight"
      stripe
      @selection-change="handleSelectionChange">
      <el-table-column
        v-if="teamEditAuth"
        :selectable="handleSelectable"
        show-overflow-tooltip
        type="selection"
        align="center"
        width="55" />
      <el-table-column
        v-for="(item, index) in fieldList"
        :key="index"
        :prop="item.prop"
        :label="item.label"
        :min-width="item.width"
        show-overflow-tooltip>
        <template slot-scope="{ row, column }">
          <wx-open-data
            v-if="column.property === 'realname'"
            :openid="row.realname" />
          <wx-open-data
            v-else-if="column.property === 'deptName'"
            :openid="row.deptName"
            type="departmentName" />
          <template v-else>{{ fieldFormatter(row,column) }}</template>
        </template>
      </el-table-column>
      <el-table-column
        prop="power"
        :label="$t('crm.components.97a929f91733f375a306cb247353e2e5')"
        min-width="100"
        show-overflow-tooltip>
        <template slot-scope="{ row, column }">
          {{ fieldFormatter(row,column) }}
          <el-tooltip
            v-if="row.power === 1 || row.power === 2"
            :content="getPowerTips(row.power)"
            style="margin-left: 3px;"
            effect="dark"
            placement="top">
            <i class="wk wk-help wk-help-tips" />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <teams-handle
      v-if="teamsDialogShow"
      :dialog-visible.sync="teamsDialogShow"
      :props="teamsHandleProps"
      :members="teamsHandleProps.type === 'add' ? null : selectionList"
      @handle="handleCallBack" />

    <el-dialog
      v-loading="loading"
      :visible.sync="editPermissionShow"
      :close-on-click-modal="false"
      :append-to-body="true"
      :title="$t('crm.components.3b1292c8adc6f67f7723c33eeaad4700')"
      width="420px">
      <div class="handle-box">
        <flexbox class="handle-item">
          <div class="handle-item-name">
            {{ $t('crm.components.db6054e6b7e6e32149969b275bcb74ce') }}
          </div>
          <el-radio-group v-model="handleType">
            <el-radio :label="1">
              {{ $t('crm.components.315250d217c3d179ea7756e6dea1b067') }}
              <el-tooltip
                style="margin-left: 3px;"
                :content="$t('crm.components.918380a12238c6915f62e1d08dc782bd')"
                effect="dark"
                placement="top">
                <i class="wk wk-help wk-help-tips" />
              </el-tooltip>
            </el-radio>
            <el-radio :label="2">
              {{ $t('crm.components.3ab76ce751b64c33b7ea4d96880d4371') }}
              <el-tooltip
                style="margin-left: 3px;"
                :content="$t('crm.components.f57519a3b0ce6f60fdcccc529292405f')"
                effect="dark"
                placement="top">
                <i class="wk wk-help wk-help-tips" />
              </el-tooltip>
            </el-radio>
          </el-radio-group>
        </flexbox>
        <flexbox class="handle-item">
          <div class="handle-item-name">
            {{ $t('crm.components.7c778a0d83b963582479e203f9236f07') }}
          </div>
          <el-select v-model="validType">
            <el-option
              :label="$t('crm.components.3bf57336fb68528e8cecdb0d47a24003')"
              value="" />
            <el-option
              :label="$t('crm.components.8cbb2c0f9d12ed0d0becbc6cc602cf25')"
              value="end" />
          </el-select>
          <el-date-picker
            v-if="validType === 'end'"
            v-model="expiresTime"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd"
            style="margin-left: 8px;"
            type="date"
            :placeholder="$t('crm.components.a8bdbd702b6358d45ffc50c997055052')" />
        </flexbox>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click.native="handleEditConfirm">
          {{ $t('crm.components.a26762645a0be12e9f3ef0ebce3774f5') }}
        </el-button>
        <el-button @click.native="editPermissionShow=false">
          {{ $t('crm.components.07496e7ccd31701ed4833b5909b242ad') }}
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script type="text/javascript">
import {
  crmCustomerTeamMembersAPI,
  crmCustomerSettingTeamSaveAPI,
  crmCustomerUpdateMembersAPI,
  crmCustomerSettingTeamDeleteAPI,
  crmCustomerExitTeamAPI
} from '@/api/crm/customer'
import {
  crmBusinessTeamMembersAPI,
  crmBusinessSettingTeamSaveAPI,
  crmBusinessUpdateMembersAPI,
  crmBusinessSettingTeamDeleteAPI,
  crmBusinessExitTeamAPI
} from '@/api/crm/business'
import {
  crmContractTeamMembersAPI,
  crmContractSettingTeamSaveAPI,
  crmContractUpdateMembersAPI,
  crmContractSettingTeamDeleteAPI,
  crmContractExitTeamAPI
} from '@/api/crm/contract'
import {
  crmContactsTeamMembersAPI,
  crmContactsSettingTeamSaveAPI,
  crmContactsUpdateMembersAPI,
  crmContactsSettingTeamDeleteAPI,
  crmContactsExitTeamAPI
} from '@/api/crm/contacts'
import {
  crmReceivablesTeamMembersAPI,
  crmReceivablesSettingTeamSaveAPI,
  crmReceivablesUpdateMembersAPI,
  crmReceivablesSettingTeamDeleteAPI,
  crmReceivablesExitTeamAPI
} from '@/api/crm/receivables'
import {
  crmReturnVisitTeamMembersAPI,
  crmReturnVisitSettingTeamSaveAPI,
  crmReturnVisitUpdateMembersAPI,
  crmReturnVisitSettingTeamDeleteAPI,
  crmReturnVisitExitTeamAPI
} from '@/api/crm/visit'

import TeamsHandle from '@/components/Page/SelectionHandle/TeamsHandle' // 操作团队成员

import { mapGetters } from 'vuex'
import { getPermissionByKey } from '@/utils'
import { getCrmHelpObj } from '../../utils'

export default {
  name: 'TeamMembers', // 团队成员  可能再很多地方展示 放到客户管理目录下
  components: {
    TeamsHandle
  },
  mixins: [],
  props: {
    // 模块ID
    id: [String, Number],
    // 联系人人下 新建商机 需要联系人里的客户信息  合同下需要客户和商机信息
    detail: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 没有值就是全部类型 有值就是当个类型
    crmType: {
      type: String,
      default: ''
    },
    // 是公海 默认是客户
    isSeas: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      list: [],
      fieldList: [
        { prop: 'realname', width: '120', label: this.$t('crm.components.cecad18693d171463ae6bb295021fb4e') },
        { prop: 'deptName', width: '100', label: this.$t('crm.components.1ba4140cc3a951b092657be34784f646') },
        { prop: 'groupRole', width: '100', label: this.$t('crm.components.3ad81676887660c93590c63506d8b3fc') },
        { prop: 'expiresTime', width: '120', label: this.$t('crm.components.54f62570455c372cdd21050990f921d9') }
      ],

      pickerOptions: {
        disabledDate(time) {
          // 当前0点时间戳
          return time.getTime() < new Date(new Date().toLocaleDateString()).getTime()
        }
      },

      tableHeight: '400px',
      teamsHandleProps: {},
      teamsDialogShow: false, // 是否展示添加团队成员窗口
      handleType: 1, // 权限类型
      validType: '', // 有效类型
      expiresTime: '', // 有效时间
      editPermissionShow: false, // 编辑权限接口展示
      selectionList: [] // 勾选的数据
    }
  },
  computed: {
    ...mapGetters(['crm']),
    teamEditAuth() {
      return !!getPermissionByKey(`crm.${this.crmType}.teamsave`)
    }
  },
  watch: {
    id(val) {
      this.list = []
      this.getDetail()
    }
  },
  mounted() {
    this.getDetail()
  },
  methods: {
    getDetail(loading = true) {
      this.loading = loading
      const request = {
        customer: crmCustomerTeamMembersAPI,
        business: crmBusinessTeamMembersAPI,
        contract: crmContractTeamMembersAPI,
        contacts: crmContactsTeamMembersAPI,
        receivables: crmReceivablesTeamMembersAPI,
        visit: crmReturnVisitTeamMembersAPI
      }[this.crmType]
      const params = {}
      params['id'] = this.id
      request(params)
        .then(res => {
          this.loading = false
          this.list = res.data
          this.$emit('data-change', this.list)
        })
        .catch(() => {
          this.loading = false
        })
    },

    fieldFormatter(row, column, cellValue) {
      // 1 只读 2 读写 3 负责人
      if (column.property === 'power') {
        return {
          1: this.$t('crm.components.b0dd30ddcc036de0b290e01d4c7c3140'),
          2: this.$t('crm.components.4e32e304d1a73b5abd86ff4ac21204b1'),
          3: this.$t('crm.components.ca28043ef1240063e415437cf029eba4')
        }[row[column.property]]
      } else if (column.property === 'groupRole') {
        return row.power === 3 ? this.$t('crm.components.c76efd1839f38923204e0d67be03de86') : this.$t('crm.components.73010ae82c2cb36b8bc3b71d1053836a')
      } else if (column.property === 'expiresTime') {
        return row.expiresTime || this.$t('crm.components.281ab82e0fa07e654c58f9bb0cabde7f')
      }

      return row[column.property] === '' || row[column.property] === null ? '--' : row[column.property]
    },

    /**
     * 当选择项发生变化时会触发该事件
     */
    handleSelectionChange(val) {
      this.selectionList = val
    },
    handleClick(type) {
      if (type == 'add') {
        // this.teamsType = 'add'
        // 团队操作
        this.teamsHandleProps = {
          type: 'add',
          addRequest: {
            customer: crmCustomerSettingTeamSaveAPI,
            contract: crmContractSettingTeamSaveAPI,
            business: crmBusinessSettingTeamSaveAPI,
            contacts: crmContactsSettingTeamSaveAPI,
            receivables: crmReceivablesSettingTeamSaveAPI,
            visit: crmReturnVisitSettingTeamSaveAPI
          }[this.crmType],
          params: { ids: [this.detail[this.crmType + 'Id']] },
          // 同时添加至联系人
          showAddType: this.crmType === 'customer',
          // 帮助提示
          readOnlyHelp: getCrmHelpObj(this.crmType, 'teamReadOnly'),
          readWriteHelp: getCrmHelpObj(this.crmType, 'teamReadWrite')
        }
        this.teamsDialogShow = true
      } else if (type == 'exit') {
        this.$confirm(
          this.$t('crm.components.1b913392d932a96efddb2b68a246d419'),
          this.$t('crm.components.063154607864d5b468af15ca40850675'),
          {
            confirmButtonText: this.$t('crm.components.5f2cae785fe7cdaf769e8f83f7eb5929'),
            cancelButtonText: this.$t('crm.components.9f253cad3a473fdb3423c144683fdbcc'),
            type: 'warning'
          }
        )
          .then(() => {
            const request = {
              customer: crmCustomerExitTeamAPI,
              business: crmBusinessExitTeamAPI,
              contract: crmContractExitTeamAPI,
              contacts: crmContactsExitTeamAPI,
              receivables: crmReceivablesExitTeamAPI,
              visit: crmReturnVisitExitTeamAPI
            }[this.crmType]

            this.loading = true
            request({ id: this.id })
              .then(res => {
                this.$message({
                  type: 'success',
                  message: this.$t('crm.components.7e789e5d97a5fcd34c2d048cc1843d92')
                })
                this.$emit('handle', { type: 'exit-team' })
                this.loading = false
              })
              .catch(() => {
                this.loading = false
              })
          })
          .catch(() => {})
      } else {
        if (this.selectionList.length == 0) {
          this.$message.error(this.$t('crm.components.7e7396658b18f75b5b095227156227b2'))
        } else {
          if (type == 'edit') {
            const editData = this.selectionList.length == 1 ? this.selectionList[0] : {}
            this.handleType = editData.power || 1
            this.validType = editData.expiresTime ? 'end' : ''
            this.expiresTime = editData.expiresTime || ''
            this.editPermissionShow = true
          } else if (type == 'delete') {
            const removeRequest = {
              customer: crmCustomerSettingTeamDeleteAPI,
              contract: crmContractSettingTeamDeleteAPI,
              business: crmBusinessSettingTeamDeleteAPI,
              contacts: crmContactsSettingTeamDeleteAPI,
              receivables: crmReceivablesSettingTeamDeleteAPI,
              visit: crmReturnVisitSettingTeamDeleteAPI
            }[this.crmType]
            if (this.crmType === 'customer') {
              this.teamsHandleProps = {
                type: 'delete',
                removeRequest: removeRequest,
                params: { ids: [this.detail[this.crmType + 'Id']] },
                // 同时添加至联系人
                showAddType: this.crmType === 'customer',
                // 帮助提示
                readOnlyHelp: getCrmHelpObj(this.crmType, 'teamReadOnly'),
                readWriteHelp: getCrmHelpObj(this.crmType, 'teamReadWrite')
              }
              this.teamsDialogShow = true
            } else {
              this.$confirm(
                this.$t('crm.components.0fddd25bc88fb214f711603378120964'),
                this.$t('crm.components.05a3b8894f553d044b8137b48adec12b'),
                {
                  confirmButtonText: this.$t('crm.components.6b848a3bfb0cce8312d862365c35ac77'),
                  cancelButtonText: this.$t('crm.components.93bf2d9f39ccd699a1212caf09fccde3'),
                  type: 'warning'
                }
              )
                .then(() => {
                  var params = {
                    ids: [this.id],
                    memberIds: this.selectionList.map(item => item.userId)
                  }

                  this.loading = true
                  removeRequest(params)
                    .then(res => {
                      this.$message({
                        type: 'success',
                        message: this.$t('crm.components.9567f0e9255611c95fcc7c3e339e8a97')
                      })
                      this.loading = false
                      this.$bus.emit('crm-tab-num-update')
                      this.getDetail()
                    })
                    .catch(() => {
                      this.loading = false
                    })
                })
                .catch(() => {})
            }
          }
        }
      }
    },

    /**
     * 添加操作
     */
    handleCallBack(data) {
      this.$bus.emit('crm-tab-num-update')
      this.getDetail()
    },

    /**
     * 编辑操作确定
     */
    handleEditConfirm() {
      if (this.validType === 'end' && !this.expiresTime) {
        this.$message.error(this.$t('crm.components.cc44fc19ae9ec463186a72f4708ab7d9'))
        return
      }
      this.loading = true
      const request = {
        customer: crmCustomerUpdateMembersAPI,
        business: crmBusinessUpdateMembersAPI,
        contract: crmContractUpdateMembersAPI,
        contacts: crmContactsUpdateMembersAPI,
        receivables: crmReceivablesUpdateMembersAPI,
        visit: crmReturnVisitUpdateMembersAPI
      }[this.crmType]
      request({
        ids: [this.id],
        memberIds: this.selectionList.map(item => item.userId),
        power: this.handleType,
        expiresTime: this.validType === 'end' ? this.expiresTime : ''
      })
        .then(res => {
          this.editPermissionShow = false
          this.$message({
            type: 'success',
            message: this.$t('crm.components.c87b5fc4ca8ba79c087b88ebbf00fc9b')
          })
          this.loading = false
          this.getDetail()
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * 返回值用来决定这一行的 CheckBox 是否可以勾选
     */
    handleSelectable(row, index) {
      // power 3 负责人 权限
      if (row.power == 3) {
        return false
      }
      return true
    },

    getPowerTips(power) {
      return {
        1: this.$t('crm.components.065dfb3bc541de6a0974188d2885dd16'),
        2: this.$t('crm.components.95fe63f7846868a648010e5dd034a258')
      }[power]
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../../styles/relativecrm.scss";

.handle-item {
  position: relative;
  padding-bottom: 15px;

  .handle-item-name {
    flex-shrink: 0;
    width: 90px;
  }

  .handle-item-content {
    flex: 1;
  }
}
</style>
